package com.tticar.invmanager.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.baomidou.mybatisplus.entity.Columns;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.shiro.LoginUser;
import com.tticar.invmanager.common.utils.DateUtils;
import com.tticar.invmanager.common.utils.PinYinUtil;
import com.tticar.invmanager.entity.SysPictrue;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.mapper.SysPictrueMapper;
import com.tticar.invmanager.service.ISysPictrueService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 图片资源 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-07-16
 */
@Service
public class SysPictrueServiceImpl extends ServiceImpl<SysPictrueMapper, SysPictrue> implements ISysPictrueService {


    private String endpoint = "oss-cn-shanghai.aliyuncs.com";
    private String accessKeyId = "LTAIdgXmN3vqbeIs";
    private String accessKeySecret = "UkzUvHJHUIa1RrLfQcO8hoQdbLcFgW";
    @Value("${oss.bucket.name}")
    private String bucketName;
    @Value("${oss.url}")
    private String ossUrl;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List upload(List<MultipartFile> file, LoginUser user, SysPictrue pictrue) throws Exception {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        List<Long> ids = new ArrayList();
        // oss 存储路径
        for (MultipartFile f : file) {
            SysPictrue pic = getPic(f, pictrue);
            pic.setPath(getObjName(user, f.getOriginalFilename()));
            pic.setCuser(user.getNickname());
            ossClient.putObject(bucketName, pic.getPath(), f.getInputStream());
            insert(pic);
            ids.add(pic.getId());
        }
        ossClient.shutdown();
        return ids;
    }

    @Override
    public String upload(MultipartFile file, String basePath) throws Exception {
        if (file == null || Strings.isBlank(file.getOriginalFilename())) {
            return "";
        }
        String url = basePath + DateUtils.getInstance().dateToString(new Date(), DateUtils.yyyyMMdd_HHmmss) + "_" + file.getOriginalFilename();
        OSS ossClient  = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata meta = new ObjectMetadata();
        meta.setCacheControl("no-cache");  // 下载时网页的缓存行为
        InputStream in = file.getInputStream();
        ossClient.putObject(bucketName, url, in);
        ossClient.shutdown();
        try {
            if(in != null){
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    @Override
    public List getByIds(String ids) {
        if (StringUtils.hasText(ids)) {
            Wrapper w = Condition.create().eq(SysPictrue.TYPE, SysPictrue.ONE).in(SysPictrue.ID, ids.split(","));
            w.setSqlSelect(Columns.create()
                    .column(SysPictrue.NAME, "caption")
                    .column(SysPictrue.ID)
                    .column(SysPictrue.SIZE)
                    .column(SysPictrue.PATH)
            );
            w.orderBy("FIELD(id," + ids + ")");
            return this.selectMaps(w);
        }
        return null;
    }

    private String getObjName(LoginUser user, String originName) {
        return "tticar-inv" + user.getTenantId() + "/" + DateFormatUtils.format(Calendar.getInstance(), "yyyyMMddHH") + "/" + PinYinUtil.getPinyinString(originName);
    }

    private SysPictrue getPic(MultipartFile file, SysPictrue pictrue) throws Exception {
        String type = file.getContentType();
        pictrue.setName(file.getOriginalFilename());
        pictrue.setType(SysPictrue.ONE);
        pictrue.setSize(file.getSize() + "");
        pictrue.setMemo(type);
        if (StringUtils.hasText(type) && type.startsWith("image")) {
            BufferedImage sourceImg = ImageIO.read(file.getInputStream());
            pictrue.setBsize(sourceImg.getWidth() + "/" + sourceImg.getHeight());
        }

        if (StringUtils.hasText(type) && type.startsWith("video")) {

        }

        return pictrue;
    }

    @Override
    public Page selectPage(SysPictrue sysPictrue, MyPage<SysPictrue> page) {
        Wrapper wrapper = new EntityWrapper().orderBy(SysPictrue.CTIME, false);
        Columns columns = Columns.create().column("*")
                .column("(select case count(1) when 0 then 'open' else 'closed' end from sys_pictrue t where t.pid=sys_pictrue.id and t.type=0)", "state");
        wrapper.setSqlSelect(columns);
        wrapper.eq(SysPictrue.TYPE, sysPictrue.getType());
        wrapper.eq(sysPictrue.getPid() != null, SysPictrue.PID, sysPictrue.getPid());
        wrapper.eq(sysPictrue.getId() != null, SysPictrue.PID, sysPictrue.getId());
        //wrapper.like(Strings.isNotEmpty(sysPictrue.getName()), SysPictrue.NAME, sysPictrue.getName());
        return this.selectMapsPage(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            SysPictrue sysPictrue = new SysPictrue();
            sysPictrue.setId(id);
            list.add(sysPictrue);
        }
        this.updateBatchById(list);
    }

}
